package com.example.helloworld;

import android.R.drawable;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceActivity extends Activity{
	
	mySurface sv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		sv = new mySurface(this);
		setContentView(sv);
	}	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_BACK){
			sv.stop();
		}
		return super.onKeyDown(keyCode, event);
	}

	private class mySurface extends SurfaceView implements SurfaceHolder.Callback{

		private DrawThread thread ;
		public mySurface(Context context) {
			super(context);
			// TODO Auto-generated constructor stub			
			getHolder().addCallback(this);
		}

		public void stop(){
			thread.setFlag(false);
		}
		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.raw.sample);
			Canvas canvas = holder.lockCanvas();
			Paint paint = new Paint();
			paint.setColor(Color.RED);
			
//			canvas.drawCircle(200, 200, 100, paint);
			canvas.drawBitmap(bitmap, 0, 0, paint);
			holder.unlockCanvasAndPost(canvas);
			
			
//			thread = new DrawThread(holder,true);
//			thread.start();
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub
			
		}
	}
	
	public class DrawThread extends Thread{
		private boolean flag = false;
		private SurfaceHolder holder;
		private Paint paint = new Paint();
		public DrawThread(SurfaceHolder holder){
			this.holder = holder;
			paint.setColor(Color.RED);
		}
		public DrawThread(SurfaceHolder holder,boolean flag){
			this(holder);
			this.flag = flag;
		}
		public void setFlag(boolean flag){
			this.flag = flag;
		}
		public void run(){
			int i=0,j=0;
			while(flag){
				Canvas canvas = holder.lockCanvas();
				canvas.drawColor(Color.WHITE);
				canvas.drawCircle(i++, j++, 50, paint);
				holder.unlockCanvasAndPost(canvas);
				try {
					sleep(1);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
